<template>
  <div>
    <van-popup
      v-model="show"
      position="top"
      :overlay="false"
      :style="{ background: background }"
    >
      <van-nav-bar
        placeholder
        fixed
        left-arrow
        :border="false"
        z-index="99"
        class="header-reading"
        @click-left="returnClick"
      >
        <template #title>
          <span :class="background == Color ? 'active' : ''">{{
            readList.title
          }}</span>
        </template>
        <template #left>
          <van-icon
            name="arrow-left"
            size="25"
            color="#fff"
            v-if="background == Color"
          />
          <van-icon name="arrow-left" size="25" color="#0A1C33" v-else />
        </template>
      </van-nav-bar>
    </van-popup>
    <!--        文章显示-->
    <div class="reading" :style="{ background: background }" ref="scroll">
      <div
        class="page-container"
        :style="{
          'font-size': fontSize + 'px',
          'line-height': lineHeight + 'px',
        }"
        @click="readingClick"
        @touchstart="touchStart"
        @touchmove="touchMove"
        @touchend="touchEnd"
      >
        <div
          v-for="(page, index) in pages"
          :key="index"
          class="page"
          :class="{ active: currentPage === index }"
          v-html="page"
        ></div>
      </div>
      <template v-if="readList.info">
        <div v-if="user_infoList.is_vip != '1'">
          <div
            class="is_pay"
            @click="show_pay = true"
            v-if="readList.coin != 0 && readList.is_pay != 1"
          >
            <p class="is_pay_title">本章需要 <span>书豆</span> 阅读</p>
            <img
              src="../../assets/images/read_menu_pay_tit.png"
              alt=""
              class="read_menu_pay_tit"
            />
          </div>
        </div>
      </template>

      <!-- <ReadingHeight
        @directoryClick="directoryClick"
        @directoryClick1="directoryClick1"
        @preId="preId"
        @nextId="nextId"
        :background="background"
        :Color="Color"
        v-if="readList.info"
      ></ReadingHeight> -->
    </div>
    <!--        侧边目录-->
    <van-popup
      v-model="show_left"
      position="left"
      style="height: 100%; width: 75%; background: #e7e7e7"
    >
      <Left
        :id="id"
        :chapterList="chapterList"
        :end="end"
        :chaps="readList.chaps"
        @chapsClick="chapsClick"
        :background="background"
        :Color="Color"
        :user_infoList="user_infoList"
        :style="{ background: background }"
      ></Left>
    </van-popup>
    <!--        底部设置-->
    <van-popup
      v-model="show"
      position="bottom"
      :overlay="false"
      class="button-reading"
      :style="{ background: background }"
    >
      <div class="mask">
        <Button
          @leftClick="leftClick"
          @backgroundClick="backgroundClick"
          @fontSizeClick="fontSizeClick"
          :value="valid"
          @preId="preId"
          @nextId="nextId"
          :background="background"
          :Color="Color"
          @switchClick="switchClick"
          :checked="checked"
          :user_infoList="user_infoList"
        ></Button>
      </div>
    </van-popup>
    <!--        阅读时间-->
    <van-popup
      v-model="show"
      position="right"
      :overlay="false"
      class="reading-right"
      :style="{ background: background }"
    >
      <div class="right" :class="background == Color ? 'active' : ''">
        <img
          src="../../assets/images/bookbean_icon.png"
          alt=""
          class="bookbean_icon"
        />
        已阅读{{ base_infoList.today_read_time }}分钟
        <van-count-down
          :time="time"
          format="ss"
          ref="countDown"
          @change="timeClick"
          @finish="finishClick"
          style="display: none"
        />
      </div>
    </van-popup>
    <!--        书豆余额-->
    <van-popup
      v-model="show"
      position="right"
      :overlay="false"
      class="reading-right dou-right"
      :style="{ background: background }"
    >
      <div class="right" :class="background == Color ? 'active' : ''">
        <img
          src="../../assets/images/bookbean_icon.png"
          alt=""
          class="bookbean_icon"
        />
        {{ base_infoList.coin }}
      </div>
    </van-popup>
    <!--        付费章节购买-->
    <van-popup
      v-model="show_pay"
      position="bottom"
      closeable
      v-if="user_infoList.is_vip != '1'"
    >
      <Pay
        :chapterList="chapterList"
        :readList="readList"
        @payList="payList"
        @topupClick="topupClick"
        @buttonClick="buttonClick"
      ></Pay>
    </van-popup>

    <van-popup v-model="logo_show" position="bottom" :style="{ height: '20%' }">
      <van-button
        type="primary"
        size="large"
        round
        class="logo-button"
        @click="onCLickAvatar"
        >登录</van-button
      >
    </van-popup>
    <!--        强制让用户关注公众号-->
    <van-overlay :show="Focus_show" @click="Focus_show = false">
      <div class="wrapper" @click.stop>
        <div class="share_arrows_div">
          <img
            src="../../assets/images/share_arrows@2x.png"
            alt=""
            class="share_arrows"
          />
        </div>
        <div class="block">
          <div>
            <p class="wrapper_title">长按识别二维码关注公众号</p>
            <p class="wrapper_subtitle">解锁更多章节</p>
          </div>
          <img :src="Focus_url" alt="" class="Focus_url_img" />
          <p class="wrapper_subtitle">已关注，请点击右上角进行刷新</p>
        </div>
      </div>
    </van-overlay>
    <!--        阅读设置弹窗-->
    <van-popup
      v-model="showSettings"
      position="bottom"
      round
      :style="{ height: '28%' }"
    >
      <div class="settings-container">
        <div class="settings-title">阅读设置</div>
        <div class="settings-content">
          <div class="settings-item">
            <span class="settings-label">字体大小</span>
            <div class="font-size-controls">
              <van-button size="small" @click="decreaseFontSize">A-</van-button>
              <span class="font-size-value">{{ fontSize }}</span>
              <van-button size="small" @click="increaseFontSize">A+</van-button>
            </div>
          </div>
          <div class="settings-item">
            <span class="settings-label">背景颜色</span>
            <div class="background-colors">
              <div
                v-for="color in backgroundColors"
                :key="color.value"
                class="color-item"
                :class="{ active: background === color.value }"
                :style="{ backgroundColor: color.value }"
                @click="changeBackground(color.value)"
              ></div>
            </div>
          </div>
        </div>
      </div>
    </van-popup>
  </div>
</template>

<script>
import Button from "../../components/ReadingView/Button";
import Left from "../../components/ReadingView/Left";
// import ReadingHeight from "../../components/ReadingHeight/ReadingList";
import Pay from "../../components/ReadingView/Pay";
import axios from "axios";

export default {
  components: {
    Button,
    Left,
    // ReadingHeight,
    Pay,
  },
  name: "Reading",
  data() {
    return {
      Focus_show: false,
      Focus_url: "",
      is_subscribe: "",
      generalize: "",
      subchaps: "",
      Color: "#543131",
      show: false,
      show_left: false,
      show_pay: false,
      logo_show: false,
      background: "#E7E7E7",
      fontSize: 23,
      lineHeight: Number,
      valid: Number,
      id: this.$route.query.id,
      readList: [],
      chapterList: [],
      end: [],
      chaps: "",
      base_infoList: [],
      time: 60 * 1000,
      time_total: 0,
      times: 0,
      Time: 60,
      checked: Boolean,
      user_infoList: {},
      self_time: 0,
      userAgent: true,
      code: "",
      showSettings: false,
      backgroundColors: [
        { name: '默认', value: '#E7E7E7' },
        { name: '护眼', value: '#C7EDCC' },
        { name: '夜间', value: '#543131' },
        { name: '纸张', value: '#F4ECD8' }
      ],
      pages: [],
      currentPage: 0,
      pageHeight: 0,
      touchStartX: 0,
      touchEndX: 0,
      touchStartY: 0,
      touchEndY: 0,
      isMoving: false,
    };
  },
  created() {
    this.self_time = parseInt(new Date().getTime() / 1000);
    if (this.$route.query.generalize) {
      this.generalize = this.$route.query.generalize;
      this.subchaps = this.$route.query.subchaps;
    } else {
      // this.generalize = localStorage.getItem('generalize')
      // this.subchaps = localStorage.getItem('subchaps')
    }
    this.chaps = this.$route.query.chaps;
    if (this.generalize && localStorage.getItem("token")) {
      // 公众号二维码
      this.is_subscribe_wechat_mp();
      this.wechat_subscribe_qrcode();
    } else {
      this.readClick();
    }
    if (/MicroMessenger/.test(window.navigator.userAgent)) {
      if (this.generalize) {
        //在微信中
        // localStorage.setItem('generalize', this.generalize)
        this.userAgent = true;
        if (!localStorage.getItem("token")) {
          this.code = this.GetUrlParam("code");
          if (this.code) {
            this.getOpenId(this.code);
          } else {
            this.WeiXin();
          }
        }
      }
    } else {
      //在浏览器中打开
      this.userAgent = false;
      localStorage.setItem("generalize", this.generalize);
    }

    this.user_info();
    this.locationClick();
    this.chapterPOST();
    this.base_info();

    // const info =
    //   "大庆，宣政殿。\r\n殿内两侧的文武百官，淡漠地注视着跪在殿中的那道身影。\r\n六皇子，你倒是解释啊，陛下还等着呢！"
     
    // this.readList.info = this.wrapParagraphsWithClass(info, "custom-class");
  },
  destroyed() {
    this.count_read_time2();
  },
  methods: {
    wechat_subscribe_qrcode() {
      this.$axios
        .post("/api/user/wechat_subscribe_qrcode", {
          scene: "anime_generalize",
          scene_data: { generalize: this.generalize },
        })
        .then((res) => {
          this.Focus_url = res.data.data.data.url;
        });
    },
    is_subscribe_wechat_mp() {
      this.$toast.loading({
        message: "加载中...",
        duration: 0,
        overlay: true,
      });
      this.$axios.post("/api/user/is_subscribe_wechat_mp").then((res) => {
        this.$toast.clear();
        this.is_subscribe = res.data.data.is_subscribe;
        this.readClick();
      });
    },
    // 授权登录
    GetUrlParam(name) {
      //封装方法
      var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
      var r = window.location.search.substr(1).match(reg); //匹配目标参数
      if (r != null) return unescape(r[2]);
      return null; //返回参数值
    },
    // 登录
    WeiXin() {
      //注意事项：回调地址必须要在公众号里进行配置回调地址才会生效
      this.code = this.GetUrlParam("code"); // 截取路径中的code，如果没有就去微信授权，如果已经获取到了就直接传code给后台获取openId
      var local = window.location.href;
      if (!this.code) {
        window.location.href =
          axios.defaults.baseURL +
          "/api/wechat_official" +
          "?redirect_uri=" +
          encodeURIComponent(local) +
          "&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect";
      } else {
        this.getOpenId(this.code); //把code传给后台获取用户信息
      }
    },
    getOpenId(code) {
      // 通过code获取 openId等用户信息，/api/user/wechat/login 为后台接口
      this.$axios
        .post("/api/wechat_official_account_login", {
          code: code,
        })
        .then((res) => {
          if (res.data.data.unregistered == "1") {
            this.$toast("授权登录");
            this.$router.push({
              path: "/replacephone?openid=" + res.data.data.openid,
            });
          } else {
            this.$toast.success("登录成功");
            localStorage.setItem("token", res.data.data.access_token);
            localStorage.setItem("openid", res.data.data.openid);
            this.$nextTick(() => {
              this.user_info();
            });
          }
        });
    },
    // 授权登录 end
    user_info() {
      this.$axios.get("/api/user_info").then((res) => {
        var res = res.data.data;
        this.user_infoList = res;
      });
    },
    returnClick() {
      this.show = false;
      if (this.chapterList.is_shelve == 1) {
        this.count_read_time(1);
        this.add_read_history();
        if (this.generalize) {
          this.$router.push({
            path: "/",
          });
        } else {
          this.$router.go(-1);
        }
      } else {
        this.$dialog
          .alert({
            title: "加入书架",
            message: "是否将本书加入书架",
            showCancelButton: "true",
            confirmButtonText: "加入书架",
            confirmButtonColor: "#4D77FD",
            cancelButtonColor: "#606266",
            cancelButtonText: "暂不加入",
          })
          .then(() => {
            this.$axios
              .get("/api/bookstores/add_to_shelve?anime_id=" + this.id)
              .then((res) => {
                if (res.data.code == 200) {
                  this.$toast(res.data.message);
                  this.count_read_time(1);
                  this.add_read_history();
                  if (this.generalize) {
                    this.$router.push({
                      path: "/",
                    });
                  } else {
                    this.$router.go(-1);
                  }
                }
              })
              .catch((err) => {
                this.$toast(err.response.data.message);
              });
          })
          .catch(() => {
            this.count_read_time(1);
            this.add_read_history();
            if (this.generalize) {
              this.$router.push({
                path: "/",
              });
            } else {
              this.$router.go(-1);
            }
          });
      }
    },
    topupClick() {
      if (!localStorage.getItem("token")) {
        this.$toast("请登录");
        return;
      }
      this.show = false;
      this.show_pay = false;
      this.count_read_time(1);
      this.add_read_history();
      this.$nextTick(() => {
        this.$router.push({
          path: "/topup",
        });
      });
    },
    buttonClick() {
      if (!localStorage.getItem("token")) {
        this.$toast("请登录");
        return;
      }
      this.show = false;
      this.show_pay = false;
      this.count_read_time(1);
      this.add_read_history();
      this.$nextTick(() => {
        this.$router.push({
          path: "/vip",
        });
      });
    },
    // 开启自动付费章节
    switchClick(checkbox) {
      if (this.user_infoList.is_vip == "1") {
        this.$toast("已开通畅读vip");
        return;
      }
      if (checkbox) {
        this.$toast("开启自动购买章节");
        localStorage.setItem("checked", "1");
      } else {
        this.$toast("关闭自动购买章节");
        localStorage.setItem("checked", "0");
      }
      this.checked = checkbox;
      if (this.readList.is_pay == "0" && this.readList.coin != "0") {
        this.payList();
      }
    },
    timeClick(e) {
      if (!localStorage.getItem("token")) {
        this.$refs.countDown.pause();
        return;
      }
      this.times = e.seconds;
    },
    finishClick() {
      this.time_total += 60;
      if (this.time_total == 120) {
        return;
      }
      this.count_read_time();
      this.$refs.countDown.reset();
    },
    // 购买章节
    payList() {
      this.$axios
        .post("/api/bookstores/pay_chapter", {
          anime_id: this.readList.anid,
          chaps: this.readList.chaps,
        })
        .then((res) => {
          if (!this.checked) {
            this.$toast("成功购买章节！");
          }
          this.chapterPOST();
          this.readClick();
        })
        .catch((err) => {
          this.$toast(err.response.data.message);
          this.show_pay = true;
          this.readList.info = this.readList.info.substr(0, 300);
        });
    },

    // 阅读时间
    count_read_time2(e) {
      this.Time = this.Time - this.times;
      var time_send = parseInt(new Date().getTime() / 1000) - this.self_time;
      this.$axios
        .get("/api/bookstores/count_read_time", {
          params: {
            time: time_send,
          },
        })
        .then((res) => {
          this.Time = 60;
          this.time_total = 0;
          if (!e) {
            this.$refs.countDown.reset();
          }
          this.base_info();
        });
    },

    // 阅读时间
    count_read_time(e) {
      return;
      this.Time = this.Time - this.times;
      this.$axios
        .get("/api/bookstores/count_read_time4", {
          params: {
            time: this.Time,
          },
        })
        .then((res) => {
          this.Time = 60;
          this.time_total = 0;
          if (!e) {
            this.$refs.countDown.reset();
          }
          this.base_info();
        });
    },
    base_info() {
      this.$axios
        .get("/api/welfare/base_info")
        .then((res) => {
          this.base_infoList = res.data.data;
        })
        .catch((err) => {
          this.$toast(err.response.data.message);
        });
    },
    nextId() {
      this.show = false;
      this.chaps = this.readList.nextId;
      if (!this.chaps) {
        this.$toast("已经是最后一页了");
        return;
      }
      this.readClick();
      this.count_read_time();
    },
    preId() {
      this.show = false;
      this.chaps = this.readList.preId;
      if (!this.chaps) {
        this.$toast("已经是第一页了");
        return;
      }
      this.readClick();
      this.count_read_time();
    },
    chapsClick(item) {
      this.chaps = item.chaps;
      this.readClick();
      this.show_left = false;
    },
    chapterPOST() {
      this.$axios
        .post("/api/bookstores/chapter", {
          anime_id: this.id,
        })
        .then((res) => {
          if (this.readList.coin != 0 && this.readList.is_pay == 0) {
            if (!localStorage.getItem("token")) {
              this.logo_show = true;
            } else {
              this.show_pay = true;
            }
          } else {
            this.show_pay = false;
          }

          var res = res.data.data;
          this.chapterList = res;
          this.end =
            this.chapterList.chapters[this.chapterList.chapters.length - 1];
        })
        .catch((err) => {
          this.$toast(err.response.data.message);
        });
    },

    wrapParagraphsWithClass(str, className) {
      // 按 \r\n 分割字符串，过滤空元素
      const paragraphs = str.split("\r\n").filter((p) => p.trim() !== "");
      // 为每个段落添加 p 标签和 class
      const wrapped = paragraphs.map((p) => `<p class="${className}" style="text-indent: 2em;line-height: 1.8;padding: 13px 0;color:#000">${p}</p>`);

      // 组合结果（如需保留原换行，可添加 \n；否则直接连接）
      return wrapped.join("");
    },

    calculatePageHeight() {
      // 计算每页可显示的高度
      const container = this.$refs.scroll;
      const containerHeight = container.clientHeight;
      
      const padding = 86; // 上下padding各40px
      this.pageHeight = containerHeight - padding;
    },
    
    splitContentIntoPages(content) {
      if (!content) return [];
      
      const paragraphs = content.split('</p>').filter(p => p.trim() !== '');
      const pages = [];
      let currentPage = '';
      let currentHeight = 0;
      
      paragraphs.forEach(paragraph => {
        const tempDiv = document.createElement('div');
        tempDiv.innerHTML = paragraph + '</p>';
        tempDiv.style.fontSize = this.fontSize + 'px';
        tempDiv.style.lineHeight = this.lineHeight + 'px';
        document.body.appendChild(tempDiv);
        
        const paragraphHeight = tempDiv.offsetHeight;
        document.body.removeChild(tempDiv);
        
        if (currentHeight + paragraphHeight > this.pageHeight) {
          pages.push(currentPage);
          currentPage = paragraph + '</p>';
          currentHeight = paragraphHeight;
        } else {
          currentPage += paragraph + '</p>';
          currentHeight += paragraphHeight;
        }
      });
      
      if (currentPage) {
        pages.push(currentPage);
      }
      
      return pages;
    },

    readClick() {
      if (this.id == sessionStorage.getItem("anime_id")) {
        this.chaps = sessionStorage.getItem("chaps");
        sessionStorage.removeItem("chaps");
        sessionStorage.removeItem("anime_id");
      }
      this.$axios
        .post("/api/bookstores/read", {
          anime_id: this.id,
          chaps: this.chaps,
        })
        .then((res) => {
          this.$refs.scroll.scrollTop = 0;
          var res = res.data.data;
          res.info = this.wrapParagraphsWithClass(res.info, "custom-class");
          this.readList = res;
          
          // 计算页面高度并分割内容
          this.$nextTick(() => {
            this.calculatePageHeight();
            this.pages = this.splitContentIntoPages(res.info);
            this.currentPage = 0;
          });
          
          if (this.user_infoList.is_vip != "1") {
            if (this.readList.coin != 0 && this.readList.is_pay != "1") {
              if (this.checked) {
                this.payList();
                return;
              }
              if (!localStorage.getItem("token")) {
                this.logo_show = true;
                sessionStorage.setItem("chaps", this.chaps);
                sessionStorage.setItem("anime_id", this.id);
                return;
              } else {
                this.show_pay = true;
              }
              this.readList.info = this.readList.info.substr(0, 300);
            }
          }
          if (this.generalize && localStorage.getItem("token")) {
            if (this.readList.chaps >= this.subchaps) {
              if (this.is_subscribe == "0") {
                this.Focus_show = true;
              }
            }
          }
        });
    },
    html_encode(str) {
      var s = "";
      if (str.length == 0) return "";
      s = str.replace(/&/g, "&amp;");
      s = s.replace(/</g, "&lt;");
      s = s.replace(/>/g, "&gt;");
      s = s.replace(/ /g, "&nbsp;");
      s = s.replace(/\'/g, "&#39;");
      s = s.replace(/\"/g, "&quot;");
      s = s.replace(/\n/g, "<br/>");
      return s;
    },
    directoryClick() {
      this.show_left = true;
    },
    directoryClick1() {
      this.showSettings = true;
    },
    locationClick() {
      if (localStorage.getItem("checked") == "1") {
        this.checked = true;
      } else {
        this.checked = false;
      }
      if (localStorage.getItem("background")) {
        this.background = localStorage.getItem("background");
      } else {
        this.background = "#E7E7E7";
      }
      if (localStorage.getItem("fontSize")) {
        this.fontSize = Number(localStorage.getItem("fontSize"));
        this.valid = this.fontSize;
        this.lineHeight = this.fontSize + 10;
      } else {
        this.fontSize = 23;
        this.valid = this.fontSize;
        this.lineHeight = this.fontSize + 10;
      }
    },
    add_read_history() {
      this.$axios
        .post("/api/bookstores/add_read_history", {
          anime_id: this.id,
          chaps: this.readList.chaps,
        })
        .then((res) => {});
    },
    readingClick() {
      this.show = !this.show;
    },
    leftClick() {
      this.show = false;
      this.show_left = true;
    },
    backgroundClick(item) {
      this.background = item;
    },
    fontSizeClick(value) {
      this.fontSize = value;
      this.valid = this.fontSize;
      this.lineHeight = this.fontSize + 20;
    },
    onCLickAvatar() {
      if (this.user_infoList) {
        this.upClick();
      } else {
        this.login();
      }
    },
    upClick() {
      if (!localStorage.getItem("token")) {
        if (this.userAgent) {
          this.WeiXin();
        } else {
          this.$router.push({
            path: "/login",
          });
        }
        return;
      }
      this.$router.push({
        path: "/up",
      });
    },
    login() {
      if (this.userAgent) {
        this.WeiXin();
      } else {
        this.$router.push({
          path: "/login",
        });
      }
    },
    increaseFontSize() {
      if (this.fontSize < 32) {
        this.fontSize += 1;
        this.lineHeight = this.fontSize + 10;
        localStorage.setItem('fontSize', this.fontSize);
      }
    },
    decreaseFontSize() {
      if (this.fontSize > 14) {
        this.fontSize -= 1;
        this.lineHeight = this.fontSize + 10;
        localStorage.setItem('fontSize', this.fontSize);
      }
    },
    changeBackground(color) {
      this.background = color;
      localStorage.setItem('background', color);
    },
    nextPage() {
      if (this.currentPage < this.pages.length - 1) {
        const currentPage = document.querySelector('.page.active');
        const nextPage = document.querySelectorAll('.page')[this.currentPage + 1];
        
        if (currentPage && nextPage) {
          currentPage.classList.add('slide-left');
          nextPage.classList.add('active');
          
          setTimeout(() => {
            currentPage.classList.remove('active', 'slide-left');
            this.currentPage++;
          }, 300);
        }
      } else {
        this.nextId()
      }
      
    },
    prevPage() {
      if (this.currentPage > 0) {
        const currentPage = document.querySelector('.page.active');
        const prevPage = document.querySelectorAll('.page')[this.currentPage - 1];
        
        if (currentPage && prevPage) {
          currentPage.classList.add('slide-right');
          prevPage.classList.add('active');
          
          setTimeout(() => {
            currentPage.classList.remove('active', 'slide-right');
            this.currentPage--;
          }, 300);
        }
      }
    },
    // 监听窗口大小变化
    handleResize() {
      this.calculatePageHeight();
      if (this.readList.info) {
        this.pages = this.splitContentIntoPages(this.readList.info);
      }
    },
    touchStart(e) {
      this.touchStartX = e.touches[0].clientX;
      this.touchStartY = e.touches[0].clientY;
      this.isMoving = true;
    },
    
    touchMove(e) {
      if (!this.isMoving) return;
      
      this.touchEndX = e.touches[0].clientX;
      this.touchEndY = e.touches[0].clientY;
      
      const diffX = this.touchEndX - this.touchStartX;
      const diffY = this.touchEndY - this.touchStartY;
      
      // 判断是水平滑动还是垂直滑动
      if (Math.abs(diffX) > Math.abs(diffY)) {
        e.preventDefault(); // 阻止默认滚动行为
        
        const currentPage = document.querySelector('.page.active');
        if (currentPage) {
          // 计算滑动距离，限制在屏幕宽度范围内
          const translateX = Math.min(Math.max(diffX, -window.innerWidth), window.innerWidth);
          currentPage.style.transform = `translateX(${translateX}px)`;
          
          // 如果有下一页，则同时移动下一页
          if (this.currentPage < this.pages.length - 1) {
            const nextPage = document.querySelectorAll('.page')[this.currentPage + 1];
            if (nextPage) {
              nextPage.style.transform = `translateX(${translateX + window.innerWidth}px)`;
            }
          }
          
          // 如果有上一页，则同时移动上一页
          if (this.currentPage > 0) {
            const prevPage = document.querySelectorAll('.page')[this.currentPage - 1];
            if (prevPage) {
              prevPage.style.transform = `translateX(${translateX - window.innerWidth}px)`;
            }
          }
        }
      }
    },
    
    touchEnd() {
      if (!this.isMoving) return;
      
      const diff = this.touchEndX - this.touchStartX;
      const threshold = window.innerWidth * 0.3; // 滑动阈值设为屏幕宽度的30%
      
      const currentPage = document.querySelector('.page.active');
      if (currentPage) {
        // 重置所有页面的transform
        document.querySelectorAll('.page').forEach(page => {
          page.style.transform = '';
        });
        
        if (Math.abs(diff) > threshold) {
          if (diff > 0) {
            // 向右滑动，上一页
            this.prevPage();
          } else {
            // 向左滑动，下一页
            this.nextPage();
          }
        }
      }
      
      this.isMoving = false;
      this.touchStartX = 0;
      this.touchEndX = 0;
    },
  },
  mounted() {
    window.addEventListener('resize', this.handleResize);
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize);
  },
};
</script>

<style scoped>
.share_arrows_div {
  position: fixed;
  top: 40px;
  right: 60px;
  color: #fff;
  text-align: right;
}

.share_arrows {
  width: 107px;
  height: 170px;
  margin-bottom: 30px;
}

.wrapper_title {
  text-align: center;
  font-size: 36px;
  padding: 30px 0 0 0;
}

.wrapper_subtitle {
  font-size: 30px;
  text-align: center;
  padding: 30px 0 0 0;
}

.Focus_url_img {
  width: 550px;
  height: 550px;
}

.wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  height: 100%;
}

.block {
  background-color: #fff;
  padding: 20px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.is_pay_title > span {
  color: #fcad0f;
}

.is_pay {
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 100px 0;
}

.is_pay_title {
  font-size: 32px;
  color: #606266;
  position: absolute;
  top: 50%;
  transform: translate(0, -50%);
}

.read_menu_pay_tit {
  height: 17px;
}

.active {
  color: #fff !important;
}

.reading-right {
  border-radius: 30px 0 0 30px;
  top: 300px;
  box-shadow: 0px 0px 18px 0px rgba(132, 134, 156, 0.2);
}

.dou-right {
  top: 200px;
}

.right {
  font-size: 24px;
  padding: 20px 40px 20px 30px;
  color: #303133;
  display: flex;
  align-items: center;
}

.bookbean_icon {
  width: 19px;
  height: 20px;
  margin-right: 10px;
  display: inline-block;
}

.button-reading {
  box-shadow: 0px 0px 18px 0px rgba(132, 134, 156, 0.1);
}

.mask {
  padding: 50px 40px;
}

.reading {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  overflow: auto;
  /* padding: 40px; */
  text-align: justify;
  font-family: -apple-system, BlinkMacSystemFont, "Helvetica Neue", Helvetica,
    Segoe UI, Arial, Roboto, "PingFang SC", "Hiragino Sans GB",
    "Microsoft Yahei", sans-serif;
}

.logo-button {
  margin-top: 80px;
}
.custom-class {
  text-indent: 2em;
}
.settings-container {
  padding: 20px;
}

.settings-title {
  font-size: 32px;
  font-weight: bold;
  text-align: center;
  margin-bottom: 20px;
}

.settings-content {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.settings-item {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.settings-label {
  font-size: 28px;
  color: #323233;
}

.font-size-controls {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 15px;
}

.font-size-value {
  min-width: 0px;
  text-align: center;
}

.background-colors {
  display: flex;
  gap: 15px;
  justify-content: space-around;
}

.color-item {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  border: 2px solid #eee;
  cursor: pointer;
  transition: all 0.3s;
}

.color-item.active {
  border-color: #1989fa;
  transform: scale(1.1);
}

.page-container {
  position: relative;
  height: 100%;
  overflow: hidden;
}

.page {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  padding: 20px 40px;
  opacity: 0;
  transition: transform 0.3s ease, opacity 0.3s ease;
  transform: translateX(0);
  will-change: transform, opacity;
  color: #000;
  touch-action: none; /* 防止触摸事件的默认行为 */
}

.page.active {
  opacity: 1;
  transform: translateX(0);
  z-index: 1;
}

.page.slide-left {
  transform: translateX(-100%);
  opacity: 0;
}

.page.slide-right {
  transform: translateX(100%);
  opacity: 0;
}
</style>